package edu.xust.MetadataGenerator.service;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import edu.xust.MetadataGenerator.domain.MetaData;
import fmpp.ProcessingException;
import fmpp.progresslisteners.ConsoleProgressListener;
import fmpp.progresslisteners.StatisticsProgressListener;
import fmpp.setting.SettingException;
import fmpp.setting.Settings;
import fmpp.util.MiscUtil;

public class Util {
	private final static Logger logger = LogManager.getLogger(Util.class);

	public static String runBAT(String[] batName) {
		String output = "";
		try {
			Process ps = Runtime.getRuntime().exec(batName);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ps.getInputStream()));
			String line;
			while (null != (line = bufferedReader.readLine())) {
				logger.debug(line);
				output += line + "\n";
			}
			bufferedReader.close();
			ps.waitFor();

		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.debug("child thread done");
		logger.debug(output);
		return output;
	}
	
	public static String relativePath(String path){
		String relative = path;
		File current = new File(".");
		String currentString = current.getAbsolutePath();
		if(path.length() >= currentString.length()){
			String head = path.substring(0, currentString.length() - 1);
			if(head.equals(currentString)){
				path = path.substring(currentString.length());
			}
		}

		return relative;
	}
	
	public static MetaData loadMetaData(String fileName) {
		MetaData metaData = null;
		try {
			File file = new File(fileName);
			String json = "";
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(new FileInputStream(file), "utf-8"));
			String str;
			while ((str = bufferedReader.readLine()) != null) {
				json += str;
			}
			bufferedReader.close();
			logger.debug(json);
			Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

			metaData = gson.fromJson(json, MetaData.class);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return metaData;
	}
	
	public static String fmpp(String source, String output, String model, String encoding){
		String result = "";
		String error = "";
	       // Shut FreeMarker logger up
        try {
        	freemarker.log.Logger.selectLoggerLibrary(freemarker.log.Logger.LIBRARY_NONE);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Failed to disable FreeMarker logging.");
        }
        // Now comes the meat...
		ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            Settings ss = new Settings(new File("."));
            
			ss.add("sourceRoot", source);
			ss.add("outputRoot", output);
			ss.add("logFile", "log.fmpp");
			ss.add("sourceEncoding", encoding);
			ss.add("data", "{doc: tdd(data/" + model + ")}");
			
			
            ss.addProgressListener(new ConsoleProgressListener(out, false));
            // - Stats
            StatisticsProgressListener stats = new StatisticsProgressListener();
            ss.addProgressListener(stats);
            
            ss.execute();
        } catch (SettingException e) {
        	error = MiscUtil.causeMessages(e);
        } catch (ProcessingException e) {
            error = MiscUtil.causeMessages(e);
		}finally{
            result = out.toString() + error;
            logger.debug(result);
		}
		return result;
	}
}
